import router from '@/router';
import axios from 'axios'
import { ElMessage } from 'element-plus';
export const baseURL = 'http://127.0.0.1:3000'
export const http = axios.create({
    baseURL: baseURL,
    timeout: 5000
})

http.interceptors.request.use(request => {
    // console.log('请求拦截器');
    const token = localStorage.getItem('token');
    if (token) {
        // console.log('本地存在token');
        request.headers['Authorization'] = `Bearer ${token}`
    }
    return request
}, error => {
    Promise.reject(error)
})

http.interceptors.response.use(response => {
    // console.log('响应拦截器');
    const { authorization } = response.headers
    localStorage.setItem('token', authorization)
    return response
}, error => {
    console.log('请求失败');
    const { status } = error.response
    console.log(status);

    if (status === 401) {
        localStorage.removeItem('token')
        ElMessage({
            type: 'error',
            message: '登录过期，请重新登录'
        })
        router.push({
            path: '/login'
        })
    }

})
